package mq.direct;

import com.rabbitmq.client.*;
import mq.Constants.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author: Themberfue
 * @date: 2025/4/27 20:05
 * @description:
 */
public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        // TODO 1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        // TODO 2. 开启信道
        Channel channel = connection.createChannel();

        // TODO 3. 声明队列，可以省略（如果生产者未声明队列的话，消费者也未声明队列则会报错，因为不知道和哪个队列绑定了）
        channel.queueDeclare(Constants.DIRECT_QUEUE1, true, false, false, null);

        // TODO 4. 接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息：" + new String(body));
            }
        };
        channel.basicConsume(Constants.DIRECT_QUEUE1, true, consumer);

        // TODO 5. 释放资源
//        channel.close(); // ! 先关闭 channel
//        connection.close();
    }
}
